<?php
/**
 * Created by PhpStorm.
 * User: leishaofa
 * Date: 2017/7/4
 * Time: 15:31
 */
class TaskAction extends CommonAction{
    protected $number=10;
    public function __construct(){
        parent::__construct();
        $siteModel=M('site','f_',C('flashSale'));
        $sitesql="select site_id,site_name from f_site where site_status = 1";
        $sitedao=$siteModel->query($sitesql);
        $this->assign('sitedao',$sitedao);
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-4
     * @parame：任务列表
     */
    public function lists(){
        $member_info=session('member_info');
        //取分页数据
        $page=is_numeric($_GET['p'])?$_GET['p']:'';
        //超级管理员
        $model=M('','',C('flashSale'));
        $where=is_numeric($_GET['site'])?'a.site_id = '.$_GET['site'].' ':'';
        $where.=is_numeric($_GET['status'])?empty($where)?'a.task_status = '.$_GET['status'].' ':' && a.task_status = '.$_GET['status'].' ':'';
        $where=empty($where)?'':' where '.$where;
        if($page) {
            $startnumber=($page-1)*$this->number;
            $listdata = $model->query("select a.*,b.site_name,b.site_status  from f_task as  a left join f_site as b ON a.site_id=b.site_id ".$where." order by a.task_id desc limit $startnumber,$this->number ");
            $listdata=array_map(function($val){
                $val['goods_time']=date('Y-m-d H:i:s',$val['goods_time']);
                $val['goods_attr']=json_decode($val['goods_attr'],true);
                $val['goods_attr']=is_array($val['goods_attr'])?$val['goods_attr']:array("allSize"=>[[],[]]);
                return $val;
            },$listdata);

            if (is_array($listdata) && !empty($listdata)) {
                return $this->ajaxReturn(array('code' => 101, 'msg' => "成功", 'data' => $listdata));
            } else {
                return $this->ajaxReturn(array('code' => 4001, 'msg' => "没有数据", 'data' => []));
            }
            exit;
        }
        /*
         * 获取团队列表
               $resultTeam=$model->query("select c.t_name,b.t_id from f_member as a left join f_member_rel as b ON a.m_id=b.m_id left join f_team as c on b.t_id=c.t_id WHERE a.m_type=1");
                $this->assign('team',$resultTeam);*/
        $resultcount=$model->query('select COUNT(*) as countnum from f_task as a '.$where);
        $this->assign('page',ceil($resultcount[0]['countnum']/$this->number));
        C('TOKEN_ON',false);
        $this->display();
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-4
     * @efect: 添加任务
     */
    public function addTask(){
        if(IS_AJAX) {
            if($_POST){
                $dao=$_POST;
                $dao['task_url']=filter_var($_POST['pro-url'], FILTER_VALIDATE_URL);
                $dao['site_id']=is_numeric($_POST['site'])?$_POST['site']:'';
                //   $dao['server_num']=is_numeric($_POST['sernumber'])?$_POST['sernumber']:'';
                //  if(empty($dao['server_num']) || $dao['server_num']>8){parent::ajaxError("线程数量不正确");}
                if(empty($dao['site_id'])){ parent::ajaxError("站点未选中");}
                if(!$dao['task_url']){ parent::ajaxError("商品链接不正确");}
                $taskmodel=M('task','f_',C('flashSale'));
                if($taskmodel->query('select task_id from f_task where task_url="'.$dao['task_url'].'" limit 1')){
                    parent::ajaxError("该商品已存在");
                }else{
                   /* if (!$taskmodel->autoCheckToken($_POST)){
                        // 令牌验证错误
                        parent::ajaxError('表单已过期！请关闭重新填写！');
                    }*/
                   //2017-11-29
                   // if($dao['pinicBuying-types'] != 1) {
                        //调用python脚本获取商品属性
                        $postData = array('pythontype' => 'getSize', 'task_url' => $dao['task_url'], 'site_id' => $dao['site_id']);
                        // $url = "";
                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, C('PYTHONURL'));
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post数据
                        curl_setopt($ch, CURLOPT_POST, 1);
// post的变量
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
                        $output = curl_exec($ch);
                     //  var_dump(curl_error($ch));
                        curl_close($ch);
                        // print_r($output);
                       // exit;
                        if (preg_match('/^\xEF\xBB\xBF/', $output)) {
                            $output = substr($output, 3);
                        }
                        $output = json_decode(trim($output), true);
                        $array = $output['data'];
                        $ret = $output['status'];
                        //exec('python '.dirname(dirname(dirname(dirname(dirname(__FILE__))))).'\python2\getSize.py '.$dao['task_url'].' '.$dao['site_id'].' 2>&1',$array,$ret);
                        if ($ret == 1) {
                            parent::ajaxError("脚本未运行");
                        }
                        if ($ret == 2) {
                            parent::ajaxError($array);
                        } else {
                            $dao['goods_attr'] = json_encode(json_decode($array[0], true));
                            // $sql='insert into f_task(team_id,server_num,site_id,task_status,task_url) VALUE ("'.$member_info['t_id'].'",'.$dao['server_num'].','.$dao['site_id'].',0,"'. $dao['task_url'].'")';

                        }
                   /* }else{
                        $dao['goods_attr']='';
                    }*/
                    $pinicBuyingTime=strtotime($dao['product-time']);
                    $sql = "insert into f_task (site_id,task_status,task_url,goods_attr,pinicBuying_types,goods_time) VALUE (" . $dao['site_id'] . ",1,'" . $dao['task_url'] . "','" . $dao['goods_attr'] . "','".htmlspecialchars($dao['pinicBuying-types'])."','".$pinicBuyingTime."')";
                    $result = $taskmodel->execute($sql);
                    if ($result) {
                        parent::ajaxSuccess("添加成功");
                    } else {
                        parent::ajaxError("添加失败");
                    }
                }
            }
            $this->display();
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-4
     * @efect:任务批量操作
     */
    public function batch(){
        if(IS_AJAX){
            $type=is_numeric($_POST['type'])?$_POST['type']:0;
            $ids=explode(',',$_POST['ids']);
            $ids=array_filter($ids);
            $page=is_numeric($_POST['p'])?$_POST['p']:0;
            $model=M('task','f_',C('flashSale'));
            if($ids[0] == 'on'){
                $startnum=($page-1)*$this->number;
                $where=is_numeric($_POST['site'])?'a.site_id = '.$_POST['site'].' ':'';
                $where.=is_numeric($_POST['status'])?empty($where)?'a.task_status = '.$_POST['status'].' ':' && a.task_status = '.$_POST['status'].' ':'';
                $where=empty($where)?'':' where '.$where;
                $query="select count(*) as pcount from (select task_id from f_task as a  ".$where." limit $startnum,$this->number) as b  ";
                $count=$model->query($query);
                if(($count[0]['pcount']+1) != count($ids)){
                    parent::ajaxError("提交数据有错误，请刷新后在尝试");
                }
                unset($ids[0]);
            }
            if($ids !== array_filter($ids,'is_numeric')){
                parent::ajaxError("选中的数据有非数字，请核对和再试");
            }
            $updateid= implode(',',$ids);
            if($type==1){
                $sql=" UPDATE f_task SET task_status = '1' WHERE task_id in (".$updateid.")";
                $updatecount=$model->execute($sql);
                parent::ajaxSuccess("成功更新".$updatecount."条数据");
            }elseif ($type==2){
                $sql=" UPDATE f_task SET task_status = '2' WHERE task_id in (".$updateid.")";
                $updatecount=$model->execute($sql);
                parent::ajaxSuccess("成功更新".$updatecount."条数据");
            }elseif ($type==3){
                $sql="DELETE FROM f_task WHERE task_id in (".$updateid.")";
                $delcount=$model->execute($sql);
                parent::ajaxSuccess("成功删除".$delcount."条数据");
            }elseif ($type==4){
                //批量更新抓取第三方网站内容
                $query="select * from  f_task as a  where a.task_id in ($updateid)";
                $list=$model->query($query);
                if(is_array($list)){
                 
                    $list=array_map(function($val){
                        if($val['site_id'] ==3) {
                            $postData = array('pythontype' => 'getSize', 'task_url' => $val['task_url'], 'site_id' => $val['site_id']);
                            // $url = "";
                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, C('PYTHONURL'));
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post数据
                            curl_setopt($ch, CURLOPT_POST, 1);
// post的变量
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
                            //print_r(curl_error($ch));
                            $output = curl_exec($ch);
                            curl_close($ch);
                            if (preg_match('/^\xEF\xBB\xBF/', $output)) {
                                $output = substr($output, 3);
                            }
                            $output = json_decode(trim($output), true);
                            $array = $output['data'];
                            $ret = $output['status'];

                            //$array=$output['data'];
                            // $ret=$output['status'];
                            //  exec('python '.dirname(dirname(dirname(dirname(dirname(__FILE__))))).'\python2\getSize.py '.$val['task_url'].' '.$val['site_id'],$array,$ret);
                            $val['shellstatus'] = $ret;//执行状态
                            $val['goodsattr'] = $dao['goods_attr'] = json_encode(json_decode($array[0], true));
                        }else{
                            $val['shellstatus'] = 1;//执行状态
                            $val['goodsattr'] = '';
                        }
                        return $val;
                    },$list);
                    $update = '';
                    foreach ($list as $val){
                        if($val['shellstatus'] == 0){
                            $update.=empty($update)?'':',';
                            $update.="(".$val['task_id'].",'".$val['server_num']."',".$val['site_id'].",'".$val['task_status']."','".$val['task_url']."','".$val['goodsattr']."')";
                        }
                    }
                    $sql="insert into f_task (task_id,server_num,site_id,task_status,task_url,goods_attr) values  ".$update." on duplicate key update task_id=values(task_id),server_num=values(server_num),site_id=values(site_id),task_status=values(task_status),task_url=values(task_url),goods_attr=values(goods_attr)";
                    $list=$model->execute($sql);
                    parent::ajaxSuccess("批量成功");
                }
                parent::ajaxError("请选择更新任务");
            }else{
                parent::ajaxError("请求url不正确");
            }
            exit;
        }
    }

    /**
     * @auth:leishaofa
     * @date:2017-07-4
     * @efect:删除任务
     */
    public function deletetask(){
        if(IS_AJAX){
            $id=is_numeric($_POST['keyid'])?$_POST['keyid']:0;
            if(empty($id)){
                parent::ajaxError("参数不存在");
            }
            $sql="delete from f_task where task_id=".$id." limit 1 ";
            $taskmodel=M('task','f_',C('flashSale'));
            $result=$taskmodel->where('task_id='.$id)->delete();
            if($result){
                parent::ajaxSuccess("删除成功");
            }else{
                parent::ajaxError("删除失败");
            }
            exit;
        }
    }
}